/**
 * Notes: 设备订单服务 - 宠物门店预约小程序
 * Date: 2025-01-27
 */

const DeviceOrderModel = require('../model/device_order_model.js');
const DeviceModel = require('../model/device_model.js');
const UserModel = require('../model/user_model.js');
const StoreModel = require('../model/store_model.js');
const timeUtil = require('../../framework/utils/time_util.js');
const AppError = require('../../framework/core/app_error.js');
const appCode = require('../../framework/core/app_code.js');
const deviceStatusManager = require('./device_status_manager.js');
const DeviceService = require('./device_service.js');
const deviceService = new DeviceService();

class DeviceOrderService {

	/**
	 * 创建设备使用订单
	 * @param {string} userId 用户ID
	 * @param {string} deviceId 设备ID
	 * @param {number} duration 使用时长（分钟）
	 * @param {string} orderType 订单类型
	 * @param {string} parentOrderId 延时订单关联的原订单ID
	 * @returns {Object} 订单信息
	 */
	async createDeviceOrder(userId, deviceId, duration, orderType = 'normal', parentOrderId = '') {
		// 验证用户是否存在
		const user = await UserModel.getOne({ _id: userId });
		if (!user) {
			throw new AppError('用户不存在', appCode.LOGIC);
		}
		
		// 验证设备是否存在（允许 mustPID=false）
		let device = await DeviceModel.getOne({ _id: deviceId }, '*', {}, false);
		if (!device) {
			device = await DeviceModel.getOne({ _id: deviceId });
		}
		if (!device) {
			throw new AppError('设备不存在', appCode.LOGIC);
		}
		
		console.log(orderType, device.status, DeviceModel.STATUS.AVAILABLE);
		if (orderType === 'normal' && device.status !== DeviceModel.STATUS.AVAILABLE) {
			throw new AppError('设备当前不可用', appCode.LOGIC);
		}
		
		const pricePerMinute = this.getDevicePricePerMinute(device.type);
		
		let startTime, endTime;
		if (orderType === 'extend' && parentOrderId) {
			const parentOrder = await DeviceOrderModel.getOne({ _id: parentOrderId });
			if (!parentOrder) throw new AppError('原订单不存在', appCode.LOGIC);
			startTime = parentOrder.endTime; // 毫秒
			endTime = startTime + duration * 60 * 1000; // 毫秒
		} else {
			startTime = timeUtil.time(); // 毫秒
			endTime = startTime + duration * 60 * 1000; // 毫秒
		}
		
		// 创建订单（强制使用设备 _id）
		const deviceOrderModel = new DeviceOrderModel();
		const orderData = {
			userId: userId,
			deviceId: device._id, // 强制保存为设备 _id
			storeId: device.storeId,
			orderType: orderType,
			parentOrderId: parentOrderId,
			duration: duration,
			pricePerMinute: pricePerMinute,
			startTime: startTime,
			endTime: endTime
		};

		// 根据前端时长套餐价计算总金额（分）
		orderData.totalAmount = this.getPackagePriceInCent(duration, pricePerMinute);

		const orderId = await deviceOrderModel.createOrder(orderData);
		if (!orderId) {
			throw new AppError('创建设备订单失败', appCode.LOGIC);
		}

		const order = await DeviceOrderModel.getOne({ _id: orderId });
		if (!order) {
			throw new AppError('获取设备订单信息失败', appCode.LOGIC);
		}

		return {
			orderId: order._id,
			orderNumber: order.orderNumber,
			deviceId: order.deviceId,
			deviceName: device.name,
			duration: order.duration,
			totalAmount: order.totalAmount,
			startTime: order.startTime,
			endTime: order.endTime,
			orderType: order.orderType
		};
	}

	/**
	 * 支付设备订单
	 * @param {string} orderId 订单ID
	 * @param {string} paymentMethod 支付方式
	 * @param {Object} paymentResult 支付结果
	 * @returns {Object} 支付结果
	 */
	async payDeviceOrder(orderId, paymentMethod, paymentResult = {}) {
		console.log(`[payDeviceOrder] 开始处理订单支付: orderId=${orderId}, method=${paymentMethod}`);
		const deviceOrderModel = new DeviceOrderModel();
		
		// 使用 getOne 绕过 PID 过滤，确保能查询到订单
		const order = await DeviceOrderModel.getOne({ _id: orderId }, '*', {}, false);
		if (!order) {
			console.error(`[payDeviceOrder] ❌ 订单不存在: ${orderId}`);
			throw new AppError('订单不存在', appCode.LOGIC);
		}
		console.log(`[payDeviceOrder] 找到订单:`, {
			orderId: order._id,
			orderNumber: order.orderNumber,
			status: order.status,
			userId: order.userId
		});

		// 检查订单状态
		if (!DeviceOrderModel.canPay(order)) {
			console.error(`[payDeviceOrder] ❌ 订单状态不允许支付: status=${order.status}`);
			throw new AppError('订单状态不允许支付', appCode.LOGIC);
		}

		if (paymentMethod === 'balance') {
			// 余额支付
			return await this.payWithBalance(order);
		} else if (paymentMethod === 'wechat_pay') {
			// 微信支付
			return await this.payWithWechat(order, paymentResult);
		} else {
			throw new AppError('不支持的支付方式', appCode.LOGIC);
		}
	}

	/**
	 * 余额支付
	 * @param {Object} order 订单信息
	 * @returns {Object} 支付结果
	 */
	async payWithBalance(order) {
		// 获取用户信息
		const user = await UserModel.getOne({ _id: order.userId });
		if (!user) {
			throw new AppError('用户不存在', appCode.LOGIC);
		}

		// 检查余额是否足够
		if (user.balance < order.totalAmount) {
			// 余额不足时，返回需要微信支付的响应
			const PaymentService = require('./payment_service.js');
			const paymentService = new PaymentService();
			const paymentParams = await paymentService.generateDeviceOrderPaymentParams(order);
			// 在调试模式且未启用真实微信支付时，标记前端模拟支付
			const config = require('../../config/config.js');
			if (config && config.TEST_MODE && !config.TEST_CONFIG.ENABLE_REAL_WECHAT_PAY) {
				paymentParams._isTestMode = true;
			}
			
			return {
				success: false,
				needWechatPay: true,
				message: '余额不足，请使用微信支付',
				orderId: order._id,
				orderNumber: order.orderNumber,
				totalAmount: order.totalAmount,
				userBalance: user.balance,
				paymentParams: paymentParams
			};
		}

		// 扣除余额
		const newBalance = user.balance - order.totalAmount;
		await UserModel.edit({ _id: order.userId }, { balance: newBalance });

		// 更新订单状态
		const deviceOrderModel = new DeviceOrderModel();
		await deviceOrderModel.updateStatus(order._id, DeviceOrderModel.STATUS.PAID, {
			payTime: timeUtil.time()
		});

		// 启动设备（如果是正常订单或延时订单的第一次支付）
		if (order.orderType === 'normal') {
			await this.startDevice(order.deviceId, order.duration, order._id, order.userId);
		} else if (order.orderType === 'extend') {
			// 修复参数顺序：extendDevice(orderId, extendMinutes, userId)
			await this.extendDevice(order._id, order.duration, order.userId);
		}

		return {
			success: true,
			message: '支付成功',
			orderId: order._id,
			remainingBalance: newBalance
		};
	}

	/**
	 * 微信支付
	 * @param {Object} order 订单信息
	 * @param {Object} paymentResult 支付结果
	 * @returns {Object} 支付结果
	 */
	async payWithWechat(order, paymentResult) {
		const { transactionId, payTime, status } = paymentResult;
		
		console.log(`💳 微信支付处理: 订单${order._id}, 状态${status}`);
		console.log('支付结果:', JSON.stringify(paymentResult, null, 2));

		if (status === 'success') {
			console.log('✅ 支付成功，开始处理后续逻辑...');
			
			// 支付成功，更新订单状态
			console.log('📝 更新订单状态为已支付...');
			const deviceOrderModel = new DeviceOrderModel();
			await deviceOrderModel.updateStatus(order._id, DeviceOrderModel.STATUS.PAID, {
				payTime: payTime || timeUtil.time(),
				transactionId: transactionId || ''
			});
			console.log('✅ 订单状态更新完成');

			// 启动设备
			console.log(`🚀 准备启动设备: ${order.deviceId}, 订单类型: ${order.orderType}`);
			if (order.orderType === 'normal') {
				console.log('启动普通设备使用...');
				await this.startDevice(order.deviceId, order.duration, order._id, order.userId);
				console.log('✅ 普通设备启动完成');
				// （逻辑已迁移到 startDevice 内进行统一处理）
			} else if (order.orderType === 'extend') {
				console.log('启动设备延时使用...');
				// 修复参数顺序：extendDevice(orderId, extendMinutes, userId)
				await this.extendDevice(order._id, order.duration, order.userId);
				console.log('✅ 设备延时启动完成');
			}

			return {
				success: true,
				message: '支付成功',
				orderId: order._id
			};
		} else {
			// 支付失败，更新订单状态
			const deviceOrderModel = new DeviceOrderModel();
			await deviceOrderModel.updateStatus(order._id, DeviceOrderModel.STATUS.CANCELLED);

			return {
				success: false,
				message: '支付失败',
				orderId: order._id
			};
		}
	}

	/**
	 * 启动设备
	 * @param {string} deviceId 设备ID
	 * @param {number} duration 使用时长（分钟）
	 * @param {string} orderId 订单ID
	 * @param {string} userId 用户ID
	 */
	async startDevice(deviceId, duration, orderId, userId) {
		// 使用统一的状态管理器，确保 remainingTime(秒) 与 endTime(毫秒) 一致
		await deviceStatusManager.startDeviceUsage(deviceId, duration, orderId, userId);
		await deviceService.controlDevice(deviceId, 'on', duration);
		// 联调需求：支付成功后 X 秒自动关闭设备（仅测试，通过配置控制）
		try {
			const config = require('../../config/config.js');
			if (config.DEVICE_AUTO_CLOSE_TEST_SECONDS > 0) {
				setTimeout(async () => {
					console.log(`⏱️ 测试自动关机: ${config.DEVICE_AUTO_CLOSE_TEST_SECONDS}s 后关闭设备 ${deviceId}`);
					try {
						await deviceStatusManager.endDeviceUsage(deviceId);
						console.log('✅ 测试自动关机完成');
					} catch (e) {
						console.error('测试自动关机失败:', e);
					}
				}, config.DEVICE_AUTO_CLOSE_TEST_SECONDS * 1000);
			}
		} catch (e) {
			console.error('插入测试自动关机逻辑失败:', e);
		}
		return { success: true };
	}

	/**
	 * 延长设备使用时间
	 * @param {string} orderId 订单ID
	 * @param {number} extendMinutes 延长时长（分钟）
	 * @param {string} userId 用户ID（可选，用于权限检查）
	 * @returns {Object} 延长结果
	 */
	async extendDevice(orderId, extendMinutes, userId = null) {
		const order = await DeviceOrderModel.getOne({ _id: orderId }, '*', {}, false);
		if (!order) throw new Error('订单不存在');

		const newEndTime = order.endTime + extendMinutes * 60 * 1000; // 毫秒
		await DeviceOrderModel.edit({ _id: orderId }, { endTime: newEndTime });
		console.log(`[订单延时] order=${orderId}, +${extendMinutes}min, newEndTime(ms)=${newEndTime}`);

		await deviceStatusManager.extendDeviceUsage(order.deviceId, extendMinutes, orderId, userId);
		return { success: true };
	}

	/**
	 * 完成设备订单
	 * @param {string} orderId 订单ID
	 * @returns {Object} 完成结果
	 */
	async completeDeviceOrder(orderId) {
		const order = await DeviceOrderModel.getOne({ _id: orderId }, '*', {}, false);
		if (!order) throw new Error('订单不存在');
	
		await DeviceOrderModel.edit({ _id: orderId }, { status: DeviceOrderModel.STATUS.COMPLETED });
	
		// 设备置为可用，remainingTime秒制
		const status = await deviceStatusManager.getDeviceRealTimeStatus(order.deviceId);
		await DeviceModel.edit({ _id: order.deviceId }, {
			status: DeviceModel.STATUS.AVAILABLE,
			remainingTime: 0,
			endTime: timeUtil.time(),
			currentOrderId: ''
		});
	
		// 由状态管理器统一负责实体设备关闭，以避免重复发送 MQTT 指令
		// await deviceService.controlDevice(order.deviceId, 'off');
		console.log(`[订单完成] device=${order.deviceId}, order=${orderId}`);
		return { success: true };
	}

	/**
	 * 获取设备每分钟价格
	 * @param {string} deviceType 设备类型
	 * @returns {number} 每分钟价格（分）
	 */
	getDevicePricePerMinute(deviceType) {
		// 这里先用固定价格，后续可以从配置表获取
		const priceConfig = {
			bath: 5,  // 洗浴池：5分/分钟
			dry: 3,   // 烘干机：3分/分钟
			blow: 2   // 吹风机：2分/分钟
		};

		return priceConfig[deviceType] || 5; // 默认5分/分钟
	}

	/**
	 * 根据前端配置的套餐价返回总金额（分）
	 * @param {number} duration 订单时长（分钟）
	 * @param {number} pricePerMinute 每分钟价格（分）作为兜底（无套餐配置时）
	 * @returns {number} 总金额（分）
	 */
	getPackagePriceInCent(duration, pricePerMinute = 0) {
		// 前端配置（单位：元）与后端对齐（单位：分）
		// 2.9, 4.9, 9.9, 14.9, 19.9, 24.9, 29.9
		const mappingYuan = {
			5: 2.9,
			10: 4.9,
			20: 9.9,
			30: 14.9,
			40: 19.9,
			50: 24.9,
			60: 29.9
		};
		if (mappingYuan[duration] != null) {
			return Math.round(mappingYuan[duration] * 100);
		}
		// 兜底：使用每分钟线性价格
		if (pricePerMinute > 0) return duration * pricePerMinute;
		return duration * this.getDevicePricePerMinute('bath'); // 默认5分/分钟
	}

	/**
	 * 获取用户设备订单列表
	 * @param {string} userId 用户ID
	 * @param {number} page 页码
	 * @param {number} size 每页数量
	 * @returns {Object} 订单列表
	 */
	async getUserDeviceOrders(userId, page = 1, size = 20) {
		const deviceOrderModel = new DeviceOrderModel();
		const result = await deviceOrderModel.getUserOrders(userId, page, size);

		// 补充设备和门店信息
		for (let order of result.list) {
			// 获取设备信息
			const device = await DeviceModel.getOne({ _id: order.deviceId });
			if (device) {
				order.deviceInfo = {
					name: device.name,
					type: device.type,
					location: device.location
				};

				// 获取门店信息
				const store = await StoreModel.getOne({ _id: device.storeId });
				if (store) {
					order.storeInfo = {
						name: store.name,
						address: store.address
					};
				}
			}

			// 添加状态描述
			order.statusDesc = DeviceOrderModel.getStatusDesc(order.status);
		}

		return result;
	}

	/**
	 * 检查并处理过期订单
	 * @returns {Object} 处理结果
	 */
	async checkExpiredOrders() {
		// 查询所有使用中的订单
		const activeOrders = await DeviceOrderModel.getAll({
			status: DeviceOrderModel.STATUS.PAID
		});

		let expiredCount = 0;
		const currentTime = timeUtil.time();

		for (let order of activeOrders) {
			if (currentTime >= order.endTime) {
				// 订单已过期，自动完成
				await this.completeDeviceOrder(order._id);
				expiredCount++;
			}
		}

		return {
			success: true,
			message: `处理了 ${expiredCount} 个过期订单`,
			expiredCount: expiredCount
		};
	}
}

module.exports = DeviceOrderService;